<?php

namespace App\Http\Controllers;

use App\Models\BalanceLog;
use App\Models\ChannelProduct;
use App\Models\CustomerProduct;
use App\Models\CzMobileBlank;
use App\Models\CzProduct;
use App\Models\CzSpec;
use App\Models\SysUser;
use App\Models\CzOrder;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Redis;

class YunController extends Controller
{
    protected $appid = '0cbcb229588e4bfb9bd3af5d055226ec';
    protected $version = '1.0';
    protected $format = 'json';
    protected $appsecret = '951626862b6b441bbeb023bf664b7b69';
    protected $page = 1;
    protected $pageSize = 100;
    protected $pageKey;
    protected $validateMobileUrl = "https://isp.qxt800.com/carrier";
    protected $validateMobileKey = "3EF892F9350A4FEA8607B8D90E461ACA";



    // protected $baseUlr = "https://openapi.aikucun.com/sandbox/rest";
    protected $baseUlr = "https://openapi.aikucun.com/route/rest";
    //
    public function __construct()
    {
        $this->pageKey = date('Ymd') . 'page';
    }
    public function getOrderBySn(Request $request)
    {
        $order_sns = request("order_sns");
        $order_sns = explode(' ', $order_sns);
        $time = request("time");
        $time = strtotime($time);
        // CzOrder::whereIn('user_order_sn',$order_sn);
        $fail_arr = [];
        $success_arr = [];
        foreach ($order_sns as $key => $val) {
            $info = CzOrder::where('user_order_sn', $val)->whereBetween('created_at', [$time, time()])->first();
            if (!$info) {
                array_push($fail_arr, $val);
            } else {
                array_push($success_arr, $val);
            }
        }
        return success([
            "fail" => $fail_arr,
            "success" => count($success_arr),
            "count" => count($order_sns),
        ]);
    }
    public function getOrderList(Request $request)
    {
        // $res = Redis::get("a");
        // dd($res);
        $pwd = request("pwd");
        $adOrderId = request("adOrderId");
        if (!$pwd) {
            return error('非法访问');
        }
        if ($pwd != 287946) {
            return error('非法访问');
        }
        $url = $this->baseUlr;
        // $url = "https://openapi.aikucun.com/route/rest";
        $user_id = 92;

        $now = time();
        $commonParams = [
            "appid" => $this->appid,
            "noncestr" => $now,
            "timestamp" => $now,
            "version" => $this->version,
            "format" => $this->format,
            "interfaceName" => "aikucun.delivery.virtual.order.list",
            "appsecret" => $this->appsecret,
        ];
        $zeroTime = strtotime(date('Y-m-d', time()));
        $start_time = date("Y-m-d H:i:s", time() - 10 * 60);
        $end_time =  date("Y-m-d H:i:s", time() + 10 * 60);
        // $end_time =  date("Y-m-d H:i:s", $zeroTime + 3600 * 24);
        // $page = Redis::get($this->pageKey);
        // var_dump('获取key' . $page);

        // if ($page) {
        //     $page = $page + 1;
        //     // Redis::set($this->pageKey, $page);
        // } else {
        //     // 初始值
        //     $page = 1;
        // }
        $page = 1;
        // var_dump('pageKey:' . $this->pageKey);
        // var_dump('page:' . $page);
        $body =  [
            "page" => $page,
            "pageSize" => $this->pageSize,
            "status" => "60",
            "startDate" => $start_time,
            "endDate" => $end_time,
            "adOrderId" => $adOrderId
        ];
        if ($body['adOrderId']) {
            // $body['page'] = 1;
            // 获取单一订单，时间重制
            $body['startDate'] = "";
            $body['endDate'] = "";
        }
        $postParams = [];
        $postParams['body'] = json_encode($body);
        $getParams = $commonParams;

        $sign = $this->getSign(array_merge($commonParams, $getParams, $postParams));
        $getParams['sign'] = $sign;

        unset($getParams['appsecret']);
        $url = $url . "?" . http_build_query($getParams);

        $headers = [
            "Content-Type:application/json"
        ];
        $res = $this->httpRequest($url, "POST", json_encode($body), '', '', $headers);
        // logger('获取订单返回数据' . $res);
        // Redis::set($this->pageKey, $page);
        // $val = Redis::del($this->pageKey);
        // var_dump($val);

        $return_arr =  json_decode($res, 1);
        // return $return_arr;
        if ($return_arr['code'] == "00000") {

            // var_dump('设置key' . $page);
            // 获取订单成功,开始下单
            // user_order_sn
            // product_id
            // spec_id
            // phone

            $orderList = $return_arr['data']['orderList'];
            // 数据的长度
            $length = count($orderList);
            if ($length < $this->pageSize) {
                // 数据加载完成或者没有订单,重制分页;
                // Redis::set($this->pageKey, 1);
                // Redis::del($this->pageKey);
            } else {
                // 还有下一页累加
                Redis::set($this->pageKey, $page);
            }
            // return $res;
            // logger('上游获取的订单:' . json_encode($orderList));
            // try {
            $is_has_arr = $this->createOrder($orderList, $user_id);
            if (count($is_has_arr) == count($orderList)) {
                // 订单中全部存在，重制分页
                // Redis::del($this->pageKey);
            }
            // } catch (\Exception $e) {
            //     return error($e->getMessage());
            // }
        } else {
            if (isset($return_arr['code'])) {
                // 失败
                logger('获取订单列表失败,原因：' . $return_arr['message']);
                return error('获取订单列表失败,原因：' . $return_arr['message']);
            }
        }
        return success([
            "page" => $page,
            "orderList" => count($orderList),
            "start_time" => $start_time,
            "end_time" => $end_time,
            // "body"=>$body,
            // "return_arr"=>$return_arr
        ]);
    }
    public function createOrder($orderList, $user_id)
    {
        $is_has_arr = [];
        foreach ($orderList as $key => $val) {
            // $this->createOrder($val);
            // dd($orderList);
            $mobile = $val['chargeAccount'];

            $face_value = substr($val['goodsList'][0]['barcode'], 6);
            // dd($face_value);
            // $face_value = substr($val['goodsList'][0]['goodsSize'], 0, strlen($val['goodsList'][0]['goodsSize']) - 1);
            $user_order_sn = $val['adorderId'];
            $goodsNo = $val['goodsList'][0]['goodsNo'];
            $barcode = $val['goodsList'][0]['barcode'];
            $pwd = '286400';

            $callback_url = env('APP_URL') . "/api/callbackOrder" . "/" . $pwd  . "/" . $goodsNo . '/' . $barcode;

            // // 验证转网
            // $validateRes = $this->validateMobile($mobile);
            // if ($validateRes['code'] == 200 && $validateRes['is_trans']) {
            //     // 转网直接返回
            //     // sock_post($callback_url,)
            //     $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, 4);
            // }

            // 验证是否下过单
            $is_order = CzOrder::where('user_order_sn', $user_order_sn)->first();

            if ($is_order) {
                array_push($is_has_arr, $user_order_sn);
                logger("订单已存在" . $user_order_sn);
                continue;
            }

            if ($this->validateMobileIsBlank($mobile)) {
                logger('号码' . $mobile . '为黑名单号码' . "订单号：" . $user_order_sn);
                var_dump('号码' . $mobile . '为黑名单号码' . "订单号：" . $user_order_sn);
                // return error('号码' . $mobile . '为黑名单号码');
                continue;
            }

            $mobile_pref = substr($mobile, 0, 7);
            // 根据手机号获取运营商
            // $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
            $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
            // if(!$mobile_info){
            //     // 不存在归属地
            // }



            $isp_name = "";
            $city_id = 0;
            $province = "";
            $city = "";
            $is_trans = 0;
            if (!$mobile_info) {
                logger($mobile . "获取归属地失败" . "订单号：" . $user_order_sn);
                var_dump($mobile . "获取归属地失败" . "订单号：" . $user_order_sn);
                // 获取未知省市
                // $mobile_info = DB::table('phone')->where('phone', "9999999")->first();
                //接口查询地区
                $areaValidate = $this->validateMobile($mobile);
                if ($areaValidate['code'] == 200) {
                    // 请求成功
                    $is_trans = $areaValidate['is_trans'];
                    if (!$areaValidate['is_has']) {
                        // 携号转网入库
                        DB::table('mobile_is_trans')->insert([
                            "mobile" => $mobile,
                            "created_at" => time(),
                            "updated_at" => time(),
                        ]);
                    }

                    if ($areaValidate['area']) {
                        $area_arr = explode('-', $areaValidate['area']);
                        $province = $area_arr[0];
                        $city = $area_arr[1];
                        $isp_name = $areaValidate['isp'];
                        // 获取area_code
                        $new_area_info = DB::table('areas')->where('province_short_name', $province)->where('city_short_name', $city)->first();
                        $city_id = $new_area_info->id;

                        // 保存至数据库
                        DB::table('phone')->insert([
                            "pref" => substr($mobile, 0, 3),
                            "phone" => substr($mobile, 0, 7),
                            "province" => $province,
                            "city" => $city,
                            "isp" => $isp_name,
                            "post_code" => $new_area_info->zip_code,
                            "city_code" => $new_area_info->city_code,
                            "area_code" => $city_id,
                        ]);
                    } else {
                        $mobile_info = DB::table('phone')->where('phone', "9999999")->first();
                        $city_id = $mobile_info->area_code;
                        $isp_name = $mobile_info->isp;
                        $province = $mobile_info->province;
                        $city = $mobile_info->city;
                    }
                } else {
                    $mobile_info = DB::table('phone')->where('phone', "9999999")->first();
                    $city_id = $mobile_info->area_code;
                    $isp_name = $mobile_info->isp;
                    $province = $mobile_info->province;
                    $city = $mobile_info->city;
                }

                // var_dump($mobile_info);
                // return error('获取归属地失败');
                // continue;
            } else {
                $city_id = $mobile_info->area_code;
                $isp_name = $mobile_info->isp;
                $province = $mobile_info->province;
                $city = $mobile_info->city;
            }



            //20220424 预防多个城市id的数据
            if (strpos($city_id, '/') !== false) {
                $city_id_exp = explode("/", $city_id);
                $city_id = $city_id_exp[0];
            }


            $isp = 0;
            switch ($isp_name) {
                case '移动':
                    $isp = 1;
                    break;
                case '移动/虚拟':
                    $isp = 1;
                    break;
                case '移动/物联网':
                    $isp = 1;
                    break;
                case '移动/未知':
                    $isp = 1;
                    break;
                case '联通':
                    $isp = 2;
                    break;
                case '联通/虚拟':
                    $isp = 2;
                    break;
                case '联通/物联网':
                    $isp = 2;
                    break;
                case '电信':
                    $isp = 3;
                    break;
                case '广电':
                    $isp = 3;
                    break;
                case '电信/虚拟':
                    $isp = 3;
                    break;
                case '电信/物联网':
                    $isp = 3;
                    break;
            }
            $area_info = DB::table('areas')->where('id', $city_id)->first();
            if (!$area_info) {
                logger($mobile . "地区信息不存在" . "订单号：" . $user_order_sn);
                var_dump($mobile . "地区信息不存在" . "订单号：" . $user_order_sn);
                continue;
            }
            $province_id = $area_info->parent_id;

            //获取用户全部产品
            // $user_id = $user_id; //用户id
            $user = SysUser::find($user_id);
            // dd($user);
            // $user_spec_id = [0];

            // 客户的所有面值
            $user_spec_id = CustomerProduct::filter(
                [
                    'user_id' => $user->id,
                    'isp' => $isp
                ]
            )->pluck('spec_id');
            // dd($user_spec_id);
            // 所有的分类
            $product_id = CzProduct::filter([
                'mobi_province_id' => $province_id,
                'mobi_city_id' => $city_id,
                'mobi_spec_id' => $user_spec_id,
                'isp' => $isp
            ])->pluck('id');
            $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
            // 比较价格
            // 获取客户产品
            $user_product = CustomerProduct::filter(
                [
                    'user_id' => $user->id,
                    'isp' => $isp
                ]
            )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
            if (!$user_product) {
                logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);

                continue;
                // return error('没有产品');
            }
            if (is_array($user_product) && !count($user_product)) {
                logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);

                continue;
                // return error('没有产品');
            }
            logger('user_product' . json_encode($user_product));
            // 优先匹配分省
            $temp_arr = $user_product->toArray();
            // var_dump($mobile_info);
            // $cur_user_product_id = $temp_arr['id'];  //默认第一个
            $cur_user_product_id = $temp_arr[0]['id'];

            foreach ($temp_arr as $key => $val) {
                $product_id = $val['product_id'];
                $prodcut = CzProduct::find($product_id);
                if ($prodcut->city_id) {
                    // 分市
                    $cur_user_product_id = $val['id'];
                    logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                    break;
                } else if ($prodcut->province_id) {
                    // 分省
                    $cur_user_product_id = $val['id'];
                    logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                    break;
                }
            }
            logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id);
            $user_product = CustomerProduct::find($cur_user_product_id);
            //获取渠道产品
            // $temp_arr = $user_product->toArray();
            // $channel_price_customer_product_id = [];



            // foreach ($temp_arr as $k => $user_p) {
            //     foreach ($user_p['channels'] as $key => $val) {
            //         $channel_product = ChannelProduct::where('spec_id', $user_p['spec_id'])->where('channel_id', $val['id']);
            //         array_push($channel_price_customer_product_id, [
            //             "channel_price" => $channel_product->channel_price,
            //             "user_product_id" => $user_p->id,
            //             "channel_id" => $val->id,
            //         ]);
            //     }
            // }
            // $cur_channel_price = $channel_price_customer_product_id[0]['channel_price'];
            // $cur_user_product_id = $channel_price_customer_product_id[0]['user_product_id'];
            // foreach()




            // $user_product = CustomerProduct::filter(
            //     [
            //         'user_id' => $user->id,
            //         'isp' => $isp
            //     ]
            // )->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->first();
            // dd($face_value);

            // 下单
            $user_price = $user_product->user_price;
            $is_loop = $user_product->is_loop;
            $submit_order_count = $user_product->submit_order_count;
            $user_product_timeout = $user_product->timeout ?? 0;

            $product_info = CzProduct::find($user_product->product_id);
            $spec_info = CzSpec::find($user_product->spec_id);
            // dd($user_product->timeout);
            $order_data = [
                'order_sn' => 'CZ' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)),
                "user_order_sn" => $user_order_sn,
                'product_name' => $product_info->title,
                'mobile' => $mobile,
                'face_value' => $spec_info->face_value,
                'cost' => $user_price,
                'price' => $user_price,
                'area_name' => $province . '-' . $city,
                'province_id' => $province_id,
                'city_id' => $city_id,
                'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
                'isp' => $product_info->isp,
                'biz_type' => $product_info->type,
                'hf_type' => $product_info->hf_type,
                'product_id' => $product_info->id,
                'spec_id' => $spec_info->id,
                'is_loop' => $is_loop,
                'submit_from' => 'api',
                'is_auto' => $spec_info->is_auto,
                'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
                "callback_url" => $callback_url,
                "create_by" => $user->id,
                "update_by" => $user->id,
            ];
            $balance_log_data = [
                'order_sn' => $order_data['order_sn'],
                'money' => $user_price,
                'bf_balance' => $user->balance,
                'af_balance' => $user->balance - $user_price,
                'bank' => '',
                'type' => 3,
                'remark' => "{$mobile},充值[{$product_info->title}{$spec_info->face_value}]，消费{$user_price}元",
                'user_id' => $user->id,
            ];
            //用户分配产品的超时时间
            if ($user_product_timeout > 0) {
                $order_data['timeout'] = time() + intval($user_product_timeout);
            }
            // dd($order_data);
            //获取订单号


            DB::beginTransaction();
            try {
                $is_dec_balance = DB::table('sys_users')
                    ->where('id', $user->id)
                    ->where('balance', '>=', ($user_price - $user->credit))
                    ->decrement('balance', $user_price);
                if (!$is_dec_balance) {
                    DB::rollBack();
                    logger($mobile . "余额不足" . "订单号：" . $user_order_sn);
                    continue;
                    // return error('余额不足');
                }
                BalanceLog::create($balance_log_data);
                // var_dump($order_data);
                $model = CzOrder::create($order_data);
                DB::commit();
            } catch (QueryException $e) {
                DB::rollBack();
                logger($mobile . '下单失败:QueryException' . "订单号：" . $user_order_sn);
                continue;
                // return error('下单失败:QueryException');
            }
            $order_id = $model->id;
            // 退款
            $refund_remark = "{$mobile},充值[{$product_info->title}{$spec_info->face_value}]，退款{$user_price}元";
            if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
                // 虚拟/物联网-号退
                DB::table('cz_order')->where('id', $order_id)->update([
                    "order_status" => 4,
                    "msg" => $isp_name,
                ]);

                $this->refund($model, $user, $refund_remark . '|' . $isp_name);
                $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, 4);
                continue;
            }
            if (strstr($isp_name, '未知')) {
                // 虚拟号退
                DB::table('cz_order')->where('id', $order_id)->update([
                    "order_status" => 4,
                    "msg" => "(获取归属地失败)未知运营商",
                ]);

                $this->refund($model, $user, $refund_remark . "|获取归属地失败,未知运营商");
                $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, 4);
                continue;
            }

            //自动订单且状态为1就推送去自动处理
            if ($order_data['is_auto'] == 1 && $order_data['order_status'] == 1) {
                // 验证转网
                if ($is_trans) {
                    // 无效号码直接返回
                    DB::table('cz_order')->where('id', $order_id)->update([
                        "order_status" => 4,
                        "msg" => "携号转网",
                    ]);

                    $this->refund($model, $user, $refund_remark . "|携号转网");
                    $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, 4);
                    continue;
                }
                $validateRes = $this->validateMobile($mobile);
                if ($validateRes['code'] == 200 && $validateRes['is_trans'] != 0) {
                    // 无效号码直接返回
                    DB::table('cz_order')->where('id', $order_id)->update([
                        "order_status" => 4,
                        "msg" => "携号转网",
                    ]);
                    if (!$validateRes['is_has']) {
                        // 数据库不存在记录在入库
                        // 携号转网入库
                        // logger("携号转网入库");
                        DB::table('mobile_is_trans')->insert([
                            "mobile" => $mobile,
                            "created_at" => time(),
                            "updated_at" => time(),
                        ]);
                    }
                    $this->refund($model, $user, $refund_remark . "|携号转网");
                    $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, 4);
                    continue;
                }
                sock_queue($order_id, 'queue_order');
            }
        }
        return $is_has_arr;
    }
    public function validateMobileIsBlank($mobile)
    {
        return  CzMobileBlank::where('mobile', $mobile)->exists();
    }
    // 退款接口
    public function refund($order, $user, $remark = '')
    {
        if ($order->is_refund == 1) {
            logger('平台退款失败:订单已退过款1' . "订单号：" . $order->order_sn);
            return ['error' => 1, 'msg' => '订单已退过款'];
        }
        //检查是否有退款记录
        $refund_info = DB::table('cz_order_refund_log')->where('order_id', $order->id)->first();
        if ($refund_info) {
            logger('平台退款失败:订单已退过款2' . "订单号：" . $order->order_sn);
            return ['error' => 1, 'msg' => '订单已退过款'];
        }
        DB::beginTransaction();
        try {
            $is_dec_balance = DB::table('sys_users')
                ->where('id', $user->id)
                ->increment('balance', $order->price);
            if (!$is_dec_balance) {
                DB::rollBack();
            }
            $res = DB::table('cz_order')->where('id', $order->id)->update([
                "is_refund" => 1,
                "updated_at" => time(),
            ]);
            if (!$res) {
                DB::rollBack();
            }
            $balance_log_data = [
                'order_sn' => $order->order_sn,
                'money' => $order->price,
                'bf_balance' => $user->balance,
                'af_balance' => $user->balance + $order->price,
                'bank' => '',
                'type' => 4,
                'remark' => $remark . "(不满足下单条件)",
                'user_id' => $user->id,
                // 'created_at' => time(),
                // 'updated_at' => time(),
            ];
            $refund_log_data = [
                'order_id' => $order->id,
                'created_at' => time(),
                'price' => $order->price,
            ];

            $b_res = BalanceLog::create($balance_log_data);
            if (!$b_res) {
                DB::rollBack();
            }
            $r_res = DB::table('cz_order_refund_log')->insert($refund_log_data);
            if (!$r_res) {
                DB::rollBack();
            }
            // var_dump($order_data);
            // $model = CzOrder::create($order_data);
            DB::commit();
        } catch (QueryException $e) {
            DB::rollBack();
            logger('平台退款失败:QueryException' . "订单号：" . $order->order_sn);
        }
    }
    public function callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, $order_status = 4)
    {
        $now = time();
        if ($order_status == 3) {
            $status = 1;
        } else {
            $status = 0;
        }
        $commonParams = [
            "appid" => $this->appid,
            "noncestr" => $now,
            "timestamp" => $now,
            "version" => $this->version,
            "format" => $this->format,
            "interfaceName" => "aikucun.delivery.virtual.order.confirm",
            "appsecret" => $this->appsecret,
        ];
        $body =  [
            "adOrderList" => [
                [
                    // "adOrderId" => "AD202108209576738700301119",
                    "adOrderId" => $user_order_sn,

                    // "chargeAccount" => "13888888888",
                    "chargeAccount" => $mobile,
                    "deliveryList" => [
                        [
                            'barcode' => $barcode,
                            'goodsNo' => $goodsNo,
                            'status' => $status,
                        ]
                    ],
                ]
            ]
        ];
        $postParams = [];
        $postParams['body'] = json_encode($body);
        $getParams = $commonParams;
        $sign = $this->getSign(array_merge($commonParams, $getParams, $postParams));
        $getParams['sign'] = $sign;
        unset($getParams['appsecret']);
        $url = $this->baseUlr;
        $url = $url . "?" . http_build_query($getParams);
        $headers = [
            "Content-Type:application/json"
        ];
        // if ($status == 1) {
        //     logger("成功不回调");
        //     return error('成功不回调');
        // }
        // sock_post($callback_url,)
        $res = $this->httpRequest($url, "POST", json_encode($body), '', '', $headers);
        // return $res;
        // logger('请求url' . $url);
        // logger('请求参数' . json_encode($body));
        logger('验证订单失败回调接口返回数据' . $res);
        $return_arr =  json_decode($res, 1);
        if ($return_arr['code'] == "00000" && $return_arr['success']) {
            // logger('回调成功:' . $order_sn);
            return success();
        } else {
            if (isset($return_arr['code'])) {
                logger('验证订单失败回调失败:' . $return_arr['message']);
                return error();
            }
        }
    }
    public function callbackOrder($pwd, $goodsNo, $barcode, Request $request)
    {
        logger('回调接口');
        logger($goodsNo);
        if (!$pwd || !$goodsNo || !$barcode) {
            return error('非法访问');
        }
        if ($pwd != 286400) {
            return error('非法访问');
        }
        // $order_status = 3;
        $order_sn = request("order_sn");
        $user_order_sn = request("user_order_sn");
        $order_status = request("order_status");
        if (!$order_sn || !$order_status) {
            return error('非法访问');
        }
        $url = $this->baseUlr;
        $order = CzOrder::where('order_sn', $order_sn)->first();
        if (!$order) {
            return error('非法访问');
        }

        $now = time();
        if ($order_status == 3) {
            $status = 1;
        } else {
            $status = 0;
        }
        $commonParams = [
            "appid" => $this->appid,
            "noncestr" => $now,
            "timestamp" => $now,
            "version" => $this->version,
            "format" => $this->format,
            "interfaceName" => "aikucun.delivery.virtual.order.confirm",
            "appsecret" => $this->appsecret,
        ];
        $body =  [
            "adOrderList" => [
                [
                    // "adOrderId" => "AD202108209576738700301119",
                    "adOrderId" => $order->user_order_sn,

                    // "chargeAccount" => "13888888888",
                    "chargeAccount" => $order->mobile,
                    "deliveryList" => [
                        [
                            'barcode' => $barcode,
                            'goodsNo' => $goodsNo,
                            'status' => $status,
                        ]
                    ],
                ]
            ]
        ];
        $postParams = [];
        $postParams['body'] = json_encode($body);
        $getParams = $commonParams;
        $sign = $this->getSign(array_merge($commonParams, $getParams, $postParams));
        $getParams['sign'] = $sign;
        unset($getParams['appsecret']);
        $url = $url . "?" . http_build_query($getParams);
        $headers = [
            "Content-Type:application/json"
        ];
        // if ($status == 1) {
        //     logger("成功不回调");
        //     return error('成功不回调');
        // }
        $res = $this->httpRequest($url, "POST", json_encode($body), '', '', $headers);
        // return $res;
        logger('请求url' . $url);
        // logger('请求参数' . json_encode($body));
        logger('回调接口返回数据' . $res);
        $return_arr =  json_decode($res, 1);
        if ($return_arr['code'] == "00000" && $return_arr['success']) {
            // logger('回调成功:' . $order_sn);
            return success();
        } else {
            if (isset($return_arr['code'])) {
                logger('回调失败:' . $return_arr['message']);
                return error();
            }
        }

        // return $barc;
    }
    public function getSign($data)
    {
        ksort($data);
        // $queryData = http_build_query($data);
        $beforeSignStr = "";
        foreach ($data as $key => $value) {
            if (!is_null($beforeSignStr) && strlen($beforeSignStr) > 0) {
                $beforeSignStr .= "&";
            }
            $beforeSignStr .= ($key . "=" . strval($value));
        }
        // var_dump($beforeSignStr);
        // logger($beforeSignStr);
        return sha1($beforeSignStr);
    }
    public function selectAreaIsp($mobile)
    {

        // $return_data = [
        //     "code" => 200,
        //     "area" => null,
        //     "is_has" => 0,
        //     "isp" => null,
        //     "msg" =>  ''
        // ];
        // $post_data = [
        //     "apikey" => $this->validateMobileKey,
        //     "mobile" => $mobile,
        // ];
        // $res = $this->httpRequest($this->validateMobileUrl, "POST", $post_data);
        // $return_arr = json_decode($res, true);
        // $return_data['msg'] =  $return_arr['reason'] ?? "";
        // if ($return_arr['code'] == 0) {

        //     if (isset($return_arr['result'])) {
        //         $return_data['area'] = $return_arr['result']['Area'] ?? "";
        //         $return_data['isp'] = $return_arr['result']['Init_isp'] ?? "";
        //     }

        //     if ($return_arr['result']['res'] == 0) {
        //         $return_data['is_trans'] = 0;
        //     } else {
        //         $return_data['is_trans'] = 1;
        //     }
        // } else {
        //     logger('接口查询异常' . $return_data['msg']);
        //     $return_data['code'] = 200;
        //     $return_data['is_trans'] = 0;
        // }
        // return $return_data;
    }
    public function validateMobile($mobile)
    {
        // 先从本地数据库验证
        $return_data = [
            "code" => 200,
            "is_trans" => 0,
            "is_has" => 0,
            "area" =>  NULL,
            "isp" =>  NULL,
            "msg" =>  ''
        ];
        $isHas = DB::table('mobile_is_trans')->where('mobile', $mobile)->first();
        if ($isHas) {
            $return_data['is_trans'] = 1;
            $return_data['is_has'] = 1;
            return $return_data;
        }
        $post_data = [
            "apikey" => $this->validateMobileKey,
            "mobile" => $mobile,
        ];
        $headers = [
            'Content-Type: application/json',
        ];
        $res = $this->httpRequest($this->validateMobileUrl, "POST", $post_data);
        $return_arr = json_decode($res, true);
        $return_data['msg'] =  $return_arr['reason'] ?? "";

        if ($return_arr['code'] == 0) {
            if (isset($return_arr['result'])) {
                $return_data['area'] = $return_arr['result']['Area'] ?? "";
                $return_data['isp'] = $return_arr['result']['Init_isp'] ?? "";
            }

            if ($return_arr['result']['res'] == 0) {
                $return_data['is_trans'] = 0;
            } else {
                $return_data['is_trans'] = 1;
            }
        } else {
            // if (isset($return_arr['code'])) {
            //     // 查询异常可正常下单
            //     logger('接口查询异常' . $return_data['msg']);
            // }
            logger('接口查询异常' . $return_data['msg']);
            $return_data['code'] = 200;
            $return_data['is_trans'] = 0;
        }
        return $return_data;
    }
    public function httpRequest($url, $method, $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 0); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 120); /* 设置cURL允许执行的最长秒数*/
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if (!$response) {
            // 请求异常才记录
            $log_file_name = __DIR__ . '/../../../storage/logs/' . date("Y-m-d") . 'request.txt';
            file_put_contents($log_file_name, "--------请求信息：---------", FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, json_encode($requestinfo) . "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, '状态码:' . $http_code, FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            if ($method == 'POST') {
                file_put_contents($log_file_name, "--------请求参数：---------", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, $tmpdatastr . "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            }
        }
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
